import React, { Component } from 'react';
import CustomForm from '../../../components/CustomForm';
import { Select, Input, message, InputNumber } from 'antd';
import { connect } from 'react-redux';
import services from '../../../services/api';
import Question from '../../../components/Question';
import { compare } from '../../../utils/compare';
import DeptSelect from '../../../components/DeptSelect';
@connect(mapStateToProps)
class TacticsEventAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      depts: [],
      applications: [],
      products: [],
      // hasRight: [],
    };
    this.actionType = 'add';
    this.form = null;
    this.api = 'event';
    this.data = this.props.value && this.props.value.event_name ? this.props.value : this.props.record;
  }

  componentDidMount() {
    this.getAppCodeList();
    this.getProductCodeList();
    // this.getDeptAll();
    if (this.actionType === 'update') {
      this.id = this.props.record.event_id;
    }
  }

  // 业务挂钩的，渠道列表请求
  getAppCodeList = ({ product_id = -1, event_id = -1 } = {}) => {
    services.application.getAppCodeList({ product_id, event_id }).then((res) => {
      if (res.code === 0) {
        this.setState({
          applications: res.data,
        });
      }
    });
  };

  // 业务挂钩的，产品列表请求
  getProductCodeList = ({ app_id = -1, event_id = -1 } = {}) => {
    services.product.getProductCodeList({ app_id, event_id }).then((res) => {
      if (res.code === 0) {
        this.setState({
          products: res.data,
        });
      }
    });
  };

  // 获取可见部门列表
  // getDeptAll = () => {
  //   services.dept.hasRight().then((res) => {
  //     if (res.code === 0) {
  //       this.setState({ hasRight: res.data });
  //     }
  //   });
  // };

  appAndProductChange = (type, value) => {
    let app_id = type === 'app_id' ? value : this.form.getFieldValue('app_id');
    let product_id = type === 'product_id' ? value : this.form.getFieldValue('product_id');
    this.getCurrentDept(app_id, product_id);
  };

  // 根据渠道/产品查询事件的可见部门
  getCurrentDept = (app_id, product_id) => {
    services.dept.getDeptByAppProduct({ app_id, product_id }).then((res) => {
      if (res.code === 0) {
        let arr = [];
        res.data.ids &&
          res.data.ids.forEach((item, index) => {
            let data = {
              label: res.data.name[index],
              value: res.data.ids[index],
            };
            arr.push(data);
          });
        this.form.setFieldsValue({ dept_ids: arr });
      }
    });
  };

  handleSubmit = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        const params = {
          app_id: values.app_id,
          product_id: values.product_id,
          event_name: values.event_name,
          event_code: values.event_code,
          gray_radio: values.gray_radio,
          remark: values.remark,
          dept_ids: values.dept_ids.map((item) => item.value),
        };
        if (this.actionType === 'update') {
          params.event_id = this.id;
        }

        services[this.api][this.actionType](params).then((data) => {
          if (data.code === 0) {
            message.success(data.msg);
            if (this.props.closeModal) {
              this.props.closeModal();
            }
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  render() {
    this.actionType = this.props.actionType;
    const { app_id, product_id, event_name, event_code, gray_radio, remark, dept_arr } = this.data || {};
    const formItems = [
      {
        label: {
          label: '所属渠道',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'app_id',
        options: {
          initialValue: app_id,
          rules: [{ required: true, message: '请选择渠道' }],
        },
        component: (
          <Select
            style={{ ...compare(this.props, 'app_id') }}
            disabled={this.actionType === 'update' || this.actionType === 'detail'}
            onChange={this.appAndProductChange.bind(this, 'app_id')}
          >
            {this.state.applications
              .filter((it) => it.app_id !== -1)
              .map((it) => {
                return (
                  <Select.Option value={it.app_id} key={it.app_id}>
                    {it.app_name}
                  </Select.Option>
                );
              })}
          </Select>
        ),
      },
      {
        label: {
          label: '关联产品',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'product_id',
        options: {
          initialValue: product_id || undefined,
        },
        component: (
          <Select
            style={{ ...compare(this.props, 'product_id') }}
            disabled={this.actionType === 'update' || this.actionType === 'detail'}
            allowClear
            onChange={this.appAndProductChange.bind(this, 'product_id')}
          >
            {this.state.products
              .filter((it) => it.app_id !== -1)
              .map((it) => {
                return (
                  <Select.Option value={it.product_id} key={it.product_id}>
                    {it.product_name}
                  </Select.Option>
                );
              })}
          </Select>
        ),
      },
      {
        label: {
          label: '事件名称',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'event_name',
        options: {
          initialValue: event_name,
          rules: [
            { required: true, message: '请填写事件名' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
          ],
        },
        component: (
          <Input
            placeholder='事件名称'
            disabled={this.actionType === 'detail'}
            style={compare(this.props, 'event_name')}
          />
        ),
      },
      {
        label: {
          label: '事件CODE',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'event_code',
        options: {
          initialValue: event_code,
          rules: [
            { required: true, message: '请填写事件Code' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[a-zA-Z][_a-zA-Z0-9]*$/, message: '限英文数字下划线，并以英文开头' },
          ],
        },
        component: (
          <Input
            placeholder='事件CODE'
            disabled={this.actionType === 'update' || this.actionType === 'detail'}
            style={compare(this.props, 'event_code')}
          />
        ),
      },
      {
        label: {
          label: '灰度',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'gray_radio',
        options: {
          rules: [{ required: true, message: '请填写灰度' }],
          initialValue: gray_radio || 1,
        },
        component: (
          <InputNumber
            min={0}
            max={1}
            step={0.1}
            disabled={this.actionType === 'detail'}
            style={compare(this.props, 'gray_radio')}
          />
        ),
        after: (
          <Question
            title={
              '灰度百分比设置，如填写1，所有请求都需要过风控引擎；如填写0.5，则请求中50%经过风控引擎，另50%请求直接通过。'
            }
          />
        ),
      },
      {
        label: {
          label: '描述',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'remark',
        options: {
          initialValue: remark,
          rules: [{ max: 256, message: '最长256个字符' }],
        },
        component: (
          <Input.TextArea
            disabled={this.actionType === 'detail'}
            style={compare(this.props, 'remark')}
            placeholder={'请填写简短描述，限256字内'}
          />
        ),
      },
      DeptSelect({
        treeCheckable: true, // 是否多选
        treeCheckStrictly: true, // 多选时是否取消父子关联
        deptTree: this.props.depts, // 全部部门数据
        deptArr: dept_arr, // 当前部门数据
        hasRight: true, // 是否需要权限展示
        // nodeDisabled: (item) => !item.dept_id, // 节点禁选
        disabled: true,
        form: this.form,
      }),
    ].filter(Boolean);

    return (
      <CustomForm
        {...this.props}
        closeModal={this.props.closeModal}
        createForm={(ref) => (this.form = ref)}
        formItems={formItems}
        onHandleSubmit={this.handleSubmit}
        colNum={1}
        hideSubmit={this.actionType === 'detail'}
      />
    );
  }
}
function mapStateToProps(state) {
  return {
    depts: state.global.depts,
  };
}
export default TacticsEventAdd;
